<?php
require_once("config.php");
require_once('data.php');

function dbc()
{
    global $g_dbc, $cfg_sql;
    
    if( isset($g_dbc) && $g_dbc ) return $g_dbc;
    
    $c = $cfg_sql;
    $g_dbc = new mysqli('localhost', $c['user'], $c['pass'], $c['dbn']) or die('DBC Error!');
    $g_dbc->set_charset("utf8");
    
    return $g_dbc;
}

function gen_key($pub_key, $prv_key)
{
    return md5($pub_key . $prv_key);
}

function gen_password($pub_key, $user_acct, $user_passwd)
{
    return md5($pub_key . $user_acct . $user_passwd);
}

function gen_cookie($user_passwd, $prv_key)
{
    return md5($user_passwd . $prv_key);
}


function new_user($user)
{
    global $cfg_key;
    
    $dbc = dbc();
    
    $passwd = gen_password($cfg_key, $user['acct_id'], $user['acct_passwd']);
    $key = md5(mt_rand() . strval(microtime(true)) . $cfg_key . $passwd);
    
    $dbc->query(sprintf("insert ignore into user values(null,0,'%s','%s','','%s','%s')",
        $dbc->escape_string($user['acct_id']),
        $dbc->escape_string($passwd),
        $dbc->escape_string($key),
        $dbc->escape_string(json_encode($user['js']))
        )
    );
    
    $id = intval($dbc->insert_id);
    if($id <= 0) {
        $dbc->query(sprintf("update user set user_passwd='%s',user_tmp_passwd='',user_key='%s',user_js='%s' where user_acct='%s' and user_flg&1=0",
            $dbc->escape_string($passwd),
            $dbc->escape_string($key),
            $dbc->escape_string(json_encode($user['js'])),
            $dbc->escape_string($user['acct_id'])
            )
        );
        $dbc->query(sprintf("select user_id from where user_acct='%s'", $dbc->escape_string($user['acct_id'])));
        if($res && ($row=$res->fetch_assoc())) $id = intval($row['user_id']);
    }
    
    return $id;
}

function set_user($user)
{
    $dbc = dbc();
    
    $dbc->query(sprintf("update user set user_js='%s' where user_id=%d and user_flg&1!=0",
        $dbc->escape_string(json_encode($user['js'])), $user['user_id']
        )
    );
}

function &get_user()
{
    global $g_user, $cfg_key;
    
    if( isset($g_user) && $g_user ) return $g_user;
    
    $g_user = array('user_id'=>0, 'user_acct'=>'', 'user_js'=>array());
    
    if( isset($_POST['user_acct']) ) {
        $clear_user_cookie = true;
        $uin_acct = strtolower(trim($_POST['user_acct']));
        $uin_passwd = trim(isset($_POST['user_passwd']) ? $_POST['user_passwd'] : '');
        $user_passwd = gen_password($cfg_key, $uin_acct, $uin_passwd);
        
        $dbc = dbc();
        $res = $dbc->query(sprintf("select * from user where user_acct='%s'",
                            $dbc->escape_string($uin_acct)
            )
        );
        if($res) {
            $lin = false;
            $row = $res->fetch_assoc();
            if($user_passwd === $row['user_passwd']) {
                $g_user['user_id'] = intval($row['user_id']);
                $g_user['user_acct'] = $row['user_acct'];
                $g_user['user_js'] = json_decode($row['user_js'], true);
                
                $key = md5(mt_rand() . strval(microtime(true)) . $cfg_key . $user_passwd);
                $dbc->query(sprintf("update user set user_flg=(user_flg|1),user_key='%s' where user_id=%d",
                            $dbc->escape_string($key), $g_user['user_id']
                    )
                );
                
                $lin = true;
                
            } elseif(!empty($row['user_tmp_passwd']) && $user_passwd === $row['user_tmp_passwd']) {
                $g_user['user_id'] = intval($row['user_id']);
                $g_user['user_acct'] = $row['user_acct'];
                $g_user['user_js'] = array();
                
                $key = md5(mt_rand() . strval(microtime(true)) . $cfg_key . $user_passwd);
                $dbc->query(sprintf("update user set user_flg=(user_flg|1),user_passwd=user_tmp_passwd,user_key='%s',user_js='{}',user_tmp_passwd='' where user_id=%d",
                            $dbc->escape_string($key), $g_user['user_id']
                    )
                );
                
                $lin = true;
                
            }
            
            if($lin) {
                $user_s = sprintf('%08u', $g_user['user_id']) . gen_key($cfg_key, $key);
                setcookie("nkl_user", $user_s, time() + 3600 * 24 * 30);
                $clear_user_cookie = false;
            }
        }
        
        if($clear_user_cookie) setcookie("nkl_user", '');
        
    } elseif( isset($_COOKIE['nkl_user']) && !empty($_COOKIE['nkl_user']) ) {
        $user_s = trim($_COOKIE['nkl_user']);
        $uid = substr($user_s, 0, 8);
        $crc = substr($user_s, 8);
        
        $dbc = dbc();
        if($res = $dbc->query( sprintf('select * from user where user_id=%d and user_flg&1!=0', intval($uid)) )) {
            $row = $res->fetch_assoc();
            if(gen_key($cfg_key, $row['user_key']) === $crc) {
                $g_user['user_id'] = intval($row['user_id']);
                $g_user['user_acct'] = $row['user_acct'];
                $g_user['user_js'] = json_decode($row['user_js'], true);
            }
        }
        
    }
    
    return $g_user;
}

function clear_user()
{
    global $cfg_key;
    
    $user = &get_user();
    if($user['user_id']) {
        $key = md5(mt_rand() . strval(microtime(true)) . $cfg_key);
        
        $dbc = dbc();
        $dbc->query(sprintf("update user set user_key='%s' where user_id=%d", $key, $user['user_id']));
    }
    
    setcookie("nkl_user", '');
}

function &get_cart()
{
    global $g_cart, $cfg_key, $CART_SEQ;

    if( isset($g_cart) && $g_cart ) return $g_cart;
    
    $g_cart = array('id'=>0, 'lst'=>array(), 'seq'=>$CART_SEQ, 'ajs'=> array('tip'=>0.0, 'fee'=>0.1));

    $cart_s = isset($_COOKIE['nkl_cart']) ? $_COOKIE['nkl_cart'] : null;
    if(!empty($cart_s)) {
        $cid = substr($cart_s, 0, 8);
        $crc = substr($cart_s, 8);
        
        $dbc = dbc();
        if($res = $dbc->query( sprintf('select * from cart where id=%d and flg=0', intval($cid)) )) {
            $row = $res->fetch_assoc();
            if(gen_key($cfg_key, $row['key']) === $crc) {
                $g_cart = $row;
                $g_cart['id'] = intval($g_cart['id']);
                $g_cart['seq'] = intval($g_cart['seq']);
                $g_cart['rev'] = intval($g_cart['rev']);
                $g_cart['flg'] = intval($g_cart['flg']);
                $g_cart['lst'] = json_decode($g_cart['lst'], true);
                $g_cart['ajs'] = json_decode($g_cart['ajs'], true);
            }
        }

    }
    
    return $g_cart;
}

function set_cart()
{
    global $g_cart, $cfg_key;

    if(!$g_cart['id'])
        $g_cart['key'] = sprintf('%u', crc32(md5(mt_rand() . strval(microtime(true)) . $cfg_key)) & 0xFFFFFFFF);

    $dbc = dbc();
    if(!$g_cart['id']) {
        $dbc->query(sprintf("insert into cart values(null, %u, 1, '%s', %u, %u, 0, '%s', '%s')",
                           $g_cart['seq'], $g_cart['key'], time(), time(),
                           $dbc->escape_string(json_encode($g_cart['lst'])),
                           $dbc->escape_string(json_encode($g_cart['ajs']))
                           )
        );
        
        $g_cart['id'] = $dbc->insert_id;
        
    } else {
        $dbc->query(sprintf("update cart set seq=%u,rev=rev+1,lst='%s',ajs='%s' where id=%d",
                           $g_cart['seq'],
                           $dbc->escape_string(json_encode($g_cart['lst'])),
                           $dbc->escape_string(json_encode($g_cart['ajs'])),
                           $g_cart['id']
                           )
        );
        
    }

    $cart_s = sprintf('%08u', $g_cart['id']) . gen_key($cfg_key, $g_cart['key']);
    setcookie("nkl_cart", $cart_s, time() + 3600 * 24 * 30);
}



function validate_cart()
{
    global $CART_SEQ, $g_menu;
    
    $cart = &get_cart();
    $lst = &$cart['lst'];

    if($cart['seq'] !== $CART_SEQ) {
        $k = 0;
        while($k < count($lst)) {
            $line = &$lst[$k];
            $l_id = intval($line['idx'] / 10);
            $l_ix = $line['idx'] % 10;
            
            if($l_id >= count($g_menu) || $l_ix >= count($g_menu[$l_id][1]) || $line['qty'] <= 0) {
                array_splice($lst, $k, 1);
                continue;
            }
            
            $item = $g_menu[$l_id];
            $line['item'] = array($item[0], $item[1][$l_ix]);
            if(empty($line['item'][0])) {
                array_splice($lst, $k, 1);
                continue;
            }
            
            $line['ex_price'] = round($line['item'][0] * $line['qty'], 2);
            $k++;
        }
        
        $cart['seq'] = $CART_SEQ;
        set_cart();
    }
    
    
}

function get_cart_total()
{
    $cart = &get_cart();
    $lst = &$cart['lst'];
    
    $sub_total = $total = $oa_total = 0.0;
    for($i = 0; $i < count($lst); $i++) {
        $line = &$lst[$i];
        $sub_total += round($line['ex_price'], 2);
    }
    if(count($lst)) {
        $sub_total = round($sub_total, 2);
        $total = round($sub_total, 2);
        $oa_total = round($total + round($cart['ajs']['fee'], 2) + round($cart['ajs']['tip'], 2), 2);
    }
    
    return array('sub_total'=> $sub_total, 'total'=> $total, 'oa_total'=> $oa_total);
}


?>